package com.lanier.dydownloader

import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.text.SpannableStringBuilder
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat.startActivity
import androidx.lifecycle.LifecycleCoroutineScope
import com.lanier.dydownloader.databinding.AtyMainBinding
import com.lanier.dydownloader.utils.ClipboardUtil
import io.wongd.lib_douyin.Douyin
import io.wongd.lib_douyin.download.DownloadService
import io.wongd.lib_douyin.ui.FgtDownload
import io.wongd.lib_douyin.ui.FgtGetXBogus
import io.wongd.lib_douyin.util.ClipUtil
import io.wongxd.solution.baseView.AtyContainer
import io.wongxd.solution.baseView.BaseRootActivityLast
import io.wongxd.solution.logger.WLogUtil
import io.wongxd.solution.util.setDropFastClick
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch


class AtyMain : BaseRootActivityLast() {

    companion object {
        val toastFlows = MutableSharedFlow<String>(extraBufferCapacity = 1)
        private const val PREFIX = "v.douyin.com/"
    }

    private lateinit var b: AtyMainBinding

    private var copyInfo = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        b = AtyMainBinding.inflate(layoutInflater)
        setContentView(b.root)

//        b.etUrl.setText("5- 长按复制此条消息，打开抖音搜索，查看TA的更多作品。 https://v.douyin.com/idoG6UTD/ 0@9.com 08/31")
//        b.etUrl.setText("8- 长按复制此条消息，打开抖音搜索，查看TA的更多作品。 https://v.douyin.com/iR8eHbW5/ 5@5.com 01/12")

        b.btnClear.setDropFastClick {
            b.etUrl.text = SpannableStringBuilder("")
        }

        b.btnByOldWV.setDropFastClick {
            copyInfo = b.etUrl.text.toString()
            if (copyInfo.isBlank()) {
                copyInfo = ClipUtil.getClipboardData(this) ?: ""
            }
            val shareLink = Douyin.getShareLink(copyInfo)
            if (shareLink.isNullOrBlank().not()) {
                startActivity(Intent(this, AtyWV::class.java).putExtra("url", shareLink))
            }
        }

        b.btnParse.setDropFastClick {
            copyInfo = b.etUrl.text.toString()
            var shareLink = Douyin.getShareLink(copyInfo)
            if (shareLink.isNullOrBlank().not()) {
//                shareLink = "http://v26-web.douyinvod.com/acb274a124867f3d845149b5afb55fa4/65546f18/video/tos/cn/tos-cn-ve-15/owNAm6nB8BenUYTC09pjABuAfpkIEDQbgl1oQD/?a=6383&ch=10010&cr=3&dr=0&lr=all&cd=0%7C0%7C0%7C3&cv=1&br=1605&bt=1605&cs=0&ds=4&ft=bvTKJbQQqUuxfdoZPo0OW_EklpPiXTRgOFVJEk1hIcbPD-I&mime_type=video_mp4&qs=0&rc=NDg3M2UzMzloOTxpOGY0ZUBpang8d2Q6ZjxvbzMzNGkzM0AvLy5fYDUuNTMxXjYuLjM2YSNlYi9jcjRvZzZgLS1kLTBzcw%3D%3D&btag=e00008000&dy_q=1700028671&feature_id=46a7bb47b4fd1280f3d3825bf2b29388&l=202311151411115E52CC8B56347811D6AA"
                startActivity(Intent(this, AtyWeb::class.java).putExtra("url", shareLink))
            }

//            if (copyInfo.isNotEmpty()) {
//                if (copyInfo.contains("http") && copyInfo.contains(PREFIX)) {
//                    val last1 = copyInfo.lastIndexOf(PREFIX)
//                    val last2 = copyInfo.lastIndexOf("/ ")
//                    val realRoute = copyInfo.substring(last1 + PREFIX.length, last2)
//                    startActivity(
//                        Intent(this, AtyWeb::class.java)
//                            .putExtra("url", "https://$PREFIX$realRoute")
//                    )
//                }
//            }
        }

        b.btnBatch.setDropFastClick {
//            val clipboardData: String = ClipUtil.getClipboardData(this)
//            if (StringUtils.isEmpty(clipboardData)) {
//                T.show("剪切板内容为空")
//                return
//            }
            copyInfo = b.etUrl.text.toString()
            if (copyInfo.isNotEmpty()) {
                AtyContainer.startFgt(this, FgtGetXBogus.newInstance(copyInfo))
            }
        }

        b.btnDownload.setDropFastClick {
            AtyContainer.startFgt(this, FgtDownload())
        }

        Douyin.init(this)

        startService(Intent(this, DownloadService::class.java))

        startService(Intent(this, com.lanier.dydownloader.download.DownloadService::class.java))

        checkPermission()

        MainScope().launch {
            toastFlows.collect {
                Log.e("下载完成", it)
                showToast(it)
            }
        }
    }

    private fun showToast(msg: CharSequence) {
        Toast.makeText(this@AtyMain, msg, Toast.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    private fun checkStorageManagerPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
            val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
            intent.data = Uri.parse("package:$packageName")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
        }
//        requestPermissions(arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE), 101)
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
//            requestPermissions(arrayOf(android.Manifest.permission.MANAGE_EXTERNAL_STORAGE), 100)
//        } else {
//            requestPermissions(arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE), 100)
//        }
    }

    private var dialog: AlertDialog? = null
    private var havePermission = false
    private fun checkPermission() {
        //检查权限（NEED_PERMISSION）是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        if (Build.VERSION.SDK_INT >= 30) {
            if (!Environment.isExternalStorageManager()) {
                dialog?.dismiss()
                dialog = null

                dialog = AlertDialog.Builder(this)
                    .setTitle("提示") //设置标题
                    .setMessage("请开启文件访问权限，否则无法正常使用本应用！")
                    .setNegativeButton("取消", DialogInterface.OnClickListener { dialog, i -> dialog.dismiss() })
                    .setPositiveButton("确定", DialogInterface.OnClickListener { dialog, which ->
                        dialog.dismiss()
                        val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
//                        intent.data = Uri.parse("package:${application.packageName}")
                        startActivity(intent)
                    }).create()
                dialog?.show()
            } else {
                havePermission = true
                Log.i("swyLog", "Android 11以上，当前已有权限")
            }
        } else {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    dialog?.dismiss()
                    dialog = null
                    dialog = AlertDialog.Builder(this)
                        .setTitle("提示") //设置标题
                        .setMessage("请开启文件访问权限，否则无法正常使用本应用！")
                        .setPositiveButton("确定", DialogInterface.OnClickListener { dialog, which ->
                            dialog.dismiss()
                            ActivityCompat.requestPermissions(
                                this,
                                arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE),
                                100
                            )
                        }).create()
                    dialog?.show()
                } else {
                    havePermission = true
                    WLogUtil.d("Android 6.0 以上 ，11 以下 ， 当前已有权限 ")
                }
            } else {
                havePermission = true
                WLogUtil.d("Android 6.0以下，已获取权限")
            }
        }
    }

}